import axios from 'axios'
// 导入toast
import { Toast } from 'vant'
import store from '@/store'
import router from '@/router/index.js'
const _axios = axios.create({
  baseURL: process.env.VUE_APP_URL
})
// 请求拦截
_axios.interceptors.request.use(
  config => {
    console.log(config)
    if (!config.noToken) {
      config.headers.Authorization = `Bearer ${store.getters['user/getToken']}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截
_axios.interceptors.response.use(
  res => {
    return res.data
  },
  error => {
    // 统一错误处理
    console.log('error', [error])
    if (error.response.data && error.response.data.message) {
      Toast.fail(error.response.data.message)
    }
    if (error.response.status === 401) {
      // 删除token
      store.commit('user/setToken', '')
      // 跳转到登录页,router.currentRoute当前路由信息
      router.push('/login?redirect=' + router.currentRoute.fullPath)
    }
    console.log('error', [error])
    return Promise.reject(error)
  }
)
export default _axios
